package com.motion.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.motion.dto.*;
import com.motion.generator.entity.*;
import com.motion.generator.mapper.FeedbackMapper;
import com.motion.provider.MobileCodeProvider;
import com.motion.provider.OSSProvider;
import com.motion.result.*;
import com.motion.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.logging.log4j.util.Strings.isBlank;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ron
 * @since 2021-3-05
 */
@RestController
@RequestMapping("/api/user")
@Api("用户管理")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private MobileCodeProvider mobileCodeProvider;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OSSProvider ossProvider;

    @Autowired
    private CourseService courseService;

    @Autowired
    private UserCourseService userCourseService;
    @Autowired
    private UserDataService userDataService;
    @Autowired
    private UserSignInDayService userLoginService;
    @Autowired
    private UserDynamicService userDynamicService;
    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private SecurityQusetionServer securityQusetionServer;
//    @RequestMapping(value = "/test", method = RequestMethod.POST)
//    public Result test() {
//        courseService.hostCourse(1L, 5L);
//        return ResultFactory.buildSuccessResult("wrx test 20210317");
//    }

    //获取验证码
    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.POST)
    @ApiOperation(value = "获取验证码",notes = "根据手机号获取短信验证码")
    public Result getVerificationCode(@RequestBody User user) {
        String phoneNumber  =  user.getPhoneNumber();
        System.out.println(phoneNumber);
        if(mobileCodeProvider.setMessage(phoneNumber)){
            return ResultFactory.buildSuccessResult(null);
        }else{
            return ResultFactory.buildFailResult("获取验证码失败");
        }
    }

    //用户登录（新用户自动注册账号）
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录",notes = "根据手机号与验证码登录")
    public Result login(@RequestBody UserLoginDto userLoginDto) {
        UserLoginDto userLoginDtoRet = new UserLoginDto();

        String phoneNumber = userLoginDto.getPhoneNumber();
        String code = userLoginDto.getCode();
        if(!redisService.exists(phoneNumber)){          //判断缓存是否已存在该用户
            return ResultFactory.buildFailResult("请先获取验证码");
        }

        if(redisService.get(phoneNumber).equals(code)){
            if(!userService.isExitUser(phoneNumber)){
                User user = new User();

                user.setPhoneNumber(phoneNumber);
                user.setCreateTime(new Date().toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
                user.setNickName("motion_"+phoneNumber.toString());
                user.setHeadPortrait("http://motion-headportrait.oss-cn-beijing.aliyuncs.com/default.jpg");
                userService.createUser(user);
                userService.updata2UserToken(user.getUserId(),StpUtil.getTokenValue());
                BeanUtils.copyProperties(user,userLoginDtoRet);
                userLoginDtoRet.setNewUser(true);
                StpUtil.setLoginId(userService.getUserId(phoneNumber));
                userLoginDtoRet.setToken(StpUtil.getTokenValue());
                return ResultFactory.buildSuccessResult(userLoginDtoRet);
            }
            //返回基本用户信息

            userService.updata2UserToken(userService.getUserId(phoneNumber),StpUtil.getTokenValue());
            BeanUtils.copyProperties(userService.phone2User(phoneNumber),userLoginDtoRet);

            userLoginDtoRet.setNewUser(false);
            StpUtil.setLoginId(userService.getUserId(phoneNumber));
            userLoginDtoRet.setToken(StpUtil.getTokenValue());
            userLoginDto.setCreateTime(userService.getTime(phoneNumber));
            System.out.println(userLoginDto);
            System.out.println(StpUtil.getLoginId());
            System.out.println(StpUtil.getTokenValueByLoginId(StpUtil.getLoginId()));
            System.out.println("1");
            return ResultFactory.buildSuccessResult(userLoginDtoRet);
        }
        return  ResultFactory.buildFailResult("验证码错误");
    }

    //上传用户头像
    //ios端
    @RequestMapping(value = "/modifyHptIos", method = RequestMethod.POST)
    @ApiOperation(value = "头像上传",notes = "token作为传入")
    public Result modifyHptIos(@RequestParam("headPortrait") MultipartFile image, @RequestParam String token){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;
        if (!image.isEmpty()) {
            try {
                String url = ossProvider.fileUpload(image.getInputStream(), String.valueOf(userId)+String.valueOf(LocalDateTime.now())+".jpg",1);
                return ResultFactory.buildSuccessResult(url);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultFactory.buildFailResult("头像上传失败" + e.getMessage());
            }
        } else {
            return ResultFactory.buildFailResult("上传头像失败");
        }
    }
    @RequestMapping(value = "/modifyHptIos2", method = RequestMethod.POST)
    @ApiOperation(value = "头像上传",notes = "useid作为传入（ios用)")
    public Result modifyHptIos2(@RequestParam("headPortrait") MultipartFile image, @RequestParam Long userId){
//        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token));
//        Long userId = 2L;
        if (!image.isEmpty()) {
            try {
//                String name=DigestUtils.md5Hex(image.getBytes());
                String url = ossProvider.fileUpload(image.getInputStream(), String.valueOf(userId)+String.valueOf(LocalDateTime.now())+".jpg",1);
//                userService.setheadurl(userId,url);
                return ResultFactory.buildSuccessResult(url);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultFactory.buildFailResult("头像上传失败" + e.getMessage());
            }
        } else {
            return ResultFactory.buildFailResult("上传头像失败");
        }
    }
    //android端
    //新头像上传,头像文件命名格式：用户ID.jpg
    @RequestMapping(value = "/modifyHptAndroid",method = RequestMethod.POST)
    @ApiOperation(value = "头像上传",notes = "token作为传入(安卓用)")
    public Result modifyHptAndroid(@RequestParam("headPortrait") MultipartFile image, @RequestParam String token){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;
        if (!image.isEmpty()) {
            try {
                String url = ossProvider.fileUpload(image.getInputStream(), String.valueOf(userId)+String.valueOf(LocalDateTime.now())+".jpg",1);
                return ResultFactory.buildSuccessResult(url);
            } catch (IOException e) {
                e.printStackTrace();
                return ResultFactory.buildFailResult("头像上传失败" + e.getMessage());
            }
        } else {
            return ResultFactory.buildFailResult("上传头像失败");
        }
    }

    //修改密码
    @RequestMapping(value = "/modifyPsw", method = RequestMethod.POST)
    @ApiOperation(value = "密码修改")
    public Result modifyPsw(@RequestBody PswDto pswDto){
        if(StpUtil.getLoginIdByToken(pswDto.getToken())==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(pswDto.getToken())));
//        Long userId = 2L;
        if (userService.modifyPsw(userId, pswDto.getNewPsw(), pswDto.getOldPsw())){
            return ResultFactory.buildSuccessResult(null);
        }
        return ResultFactory.buildFailResult("密码错误");
    }
    //忘记密码
    @RequestMapping(value = "/changePsw", method = RequestMethod.POST)
    @ApiOperation(value = "忘记密码")
    public Result changePsw(@RequestBody PswDto pswDto){
        if(StpUtil.getLoginIdByToken(pswDto.getToken())==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(pswDto.getToken())));
//        Long userId = 2L;
        User user=userService.getUserById(userId);
        user.setPassword(pswDto.getNewPsw());
        if (userService.updateUser(user)!=null){
            return ResultFactory.buildSuccessResult(null);
        }
        return ResultFactory.buildFailResult("密码错误");
    }

    //修改用户信息
    @RequestMapping(value = "/setProfile", method = RequestMethod.POST)
    @ApiOperation(value = "修改用户信息")
    public Result setProfile(@RequestBody UserLoginDto userLoginDto) {
        System.out.println(userLoginDto);
        UserLoginDto userLoginDtoRet = new UserLoginDto();
        boolean user_changed = false;
        boolean userData_changed = false;

        User user = new User();
        UserData userData = new UserData();

        Long userId = userLoginDto.getUserId();
        user.setUserId(userId);
        userData.setUserId(userId);

        if (!isBlank(userLoginDto.getNickname())){
            user.setNickName(userLoginDto.getNickname());
            user_changed = true;
        }
        if (!isBlank(userLoginDto.getHeadPortraitUrl())){
            user.setHeadPortrait(userLoginDto.getHeadPortraitUrl());
            user_changed = true;
        }
        if (!isBlank(userLoginDto.getGender().toString())) {
            user.setGender(userLoginDto.getGender());
            user_changed = true;
        }
        if (!(userLoginDto.getWeight() == 0)){
            userData.setWeight(userLoginDto.getWeight());
            userData_changed = true;
        }
        if (!(userLoginDto.getHeight() == 0)) {
            userData.setHeight(userLoginDto.getHeight());
            userData_changed = true;
        }

        try{
            if (user_changed){
                userService.updateUser(user);
            }
            if (userData_changed){
                if (userDataService.isExistUserData(userLoginDto.getUserId())){
                    userDataService.updateUserData(userData);
                }else {
                    userDataService.creatUserData(userData);
                }
            }

            StpUtil.setLoginId(userId);
            userLoginDtoRet.setToken(StpUtil.getTokenValue());
            return ResultFactory.buildSuccessResult(userLoginDtoRet);
        }catch (Exception e){
            return ResultFactory.buildFailResult("fail to update");
        }
    }


    //我的收藏
    @RequestMapping(value = "/userHasCollected", method = RequestMethod.GET)
    @ApiOperation(value = "用户收藏")
    public Result userHasCollected(@RequestParam String token, @RequestParam Long page, @RequestParam Long size){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;
        return ResultFactory.buildSuccessResult(userCourseService.userHasCollected(userId, page, size));

    }

    //我的预订
    @RequestMapping(value = "/userHasBooked", method = RequestMethod.GET)
    @ApiOperation(value = "用户预定")
    public Result userHasBooked(@RequestParam String token, @RequestParam Long page, @RequestParam Long size){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId = 2L;
        return ResultFactory.buildSuccessResult(userCourseService.userHasBooked(userId, page, size));

    }
    //运动中心日志数据
    @RequestMapping(value = "/getSportsLogData", method = RequestMethod.GET)
    @ApiOperation(value = "运动中心日志数据")
    public Result getSignInDayList(@RequestParam String token){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=Long.valueOf(token);
        List<UserSignInDay> result=userLoginService.getSignInDay(userId);
        return ResultFactory.buildSuccessResult(result);
    }
    //运动中心数据
    @RequestMapping(value = "/getSportsCenterData", method = RequestMethod.GET)
    @ApiOperation(value = "运动中心数据")
    public Result getSportsCenterData(@RequestParam String token){
        //假token
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=Long.valueOf(token);
        SportsCenterDataDto result=new SportsCenterDataDto();
        UserDynamic userDynamic=userDynamicService.getUserDynamicByUserId(userId);
        result.setContinueDaysCount(userDynamic.getMaxDay());
        result.setExerciseTimeCount(userDynamic.getTrainDuration());
        User user=userService.getUserById(userId);
        result.setDaysCount(Duration.between(user.getCreateTime(), LocalDateTime.now()).toDays());
        result.setCourseCount(userCourseService.getUserCoursecount(userId));
        return ResultFactory.buildSuccessResult(result);
    }
    //获取查看用户反馈
    @RequestMapping(value = "/getFeedback", method = RequestMethod.GET)
    @ApiOperation(value = "获取查看用户反馈")
    public Result getFeedback(@RequestParam String token,@RequestParam Long page,@RequestParam Long size ){
        //假token
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId=Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=Long.valueOf(token);
        IPage<Feedback> feedbackIPage=feedbackService.getFeedbackPage(userId,page,size);
        FeedbackListDto resulf=new FeedbackListDto();
        resulf.setHasNext(page*size<feedbackIPage.getTotal());
        resulf.setMyFeedbackList(feedbackIPage.getRecords());
        return ResultFactory.buildSuccessResult(resulf);
    }
    //修改手机号
    @RequestMapping(value = "/changePhone", method = RequestMethod.POST)
    @ApiOperation(value = "修改手机号")
    public Result changePhone(@RequestBody PhoneDto phoneDto){
        String token=phoneDto.getToken();
        String phoneNumber=phoneDto.getPhoneNumber();
        String code=phoneDto.getCode();
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
//        Long userId=6L;
        User user = userService.getUserById(userId);
        user.setPhoneNumber(phoneNumber);
        if(!redisService.exists(phoneNumber)){          //判断缓存是否已存在该用户
            return ResultFactory.buildFailResult("请先获取验证码");
        }
        boolean is=redisService.get(phoneNumber).equals(code);
        User user2=userService.phone2User(phoneNumber);
        if (user2!=null){
            return ResultFactory.buildFailResult("手机号已被注册");
        }
        if( is) {
            User user1=userService.updateUser(user);
            return ResultFactory.buildSuccessResult(user1.getPhoneNumber());
        }
        else{
                return ResultFactory.buildFailResult("验证码错误");
            }
    }
    //用户反馈
    @RequestMapping(value = "/sendFeedback", method = RequestMethod.POST)
    @ApiOperation(value = "用户反馈")
    public Result sendFeedback(@RequestBody FeedbackDto feedbackDto){
        if(StpUtil.getLoginIdByToken(feedbackDto.getToken())==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(feedbackDto.getToken())));
        Feedback feedback=new Feedback();
        feedback.setContent(feedbackDto.getFeedbackContent());
        feedback.setCreateTime(LocalDateTime.now());
        feedback.setUserId(userId);
        feedback.setPicUrls(feedbackDto.getFeedbackImg());
        feedback.setQQnumber(feedbackDto.getFeedbackQQ());
        feedbackService.insertFeedback(feedback);
        return ResultFactory.buildSuccessResult("成功");
    }
    @RequestMapping(value = "/getFeedbackById", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户反馈")
    public Result getFeedbackById(@RequestParam Long feedbackId){
        Feedback resulf=feedbackService.getFeedbackById(feedbackId);
        if (resulf!=null) {
            return ResultFactory.buildSuccessResult(feedbackService.getFeedbackById(feedbackId));
        }else {
            return ResultFactory.buildFailResult("id不存在");
        }
    }

    //用户登录（新用户自动注册账号）
    @RequestMapping(value = "/accountLogin", method = RequestMethod.POST)
    @ApiOperation(value = "登录",notes = "根据账号密码登录")
    public Result accountLogin(@RequestBody UserLoginDto userLoginDto) {
//        String token=accountDto.getToken();
//        if(StpUtil.getLoginIdByToken(token)==null){
//            return ResultFactory.buildResultTokenError("token无效");
//        }
        String account=userLoginDto.getAccount();
        String password=userLoginDto.getPassword();
        if(userService.getUserByAccount(account)==null)
            return ResultFactory.buildFailResult("无账号");
        User user=userService.acount2userId(account,password);
        if (user!=null){
            user.setToken(StpUtil.getTokenValue());
            return ResultFactory.buildSuccessResult(user);
        }
        return ResultFactory.buildFailResult("密码错误");
    }

    @RequestMapping(value = "/login2",method = RequestMethod.GET)
    public Result login2(@RequestParam String account,@RequestParam String password){
        boolean dw=userService.cheak(account,password);
        if(dw){
            return ResultFactory.buildSuccessResult("成功");
        }else {
            return ResultFactory.buildFailResult("失败");
        }
    }
    //每日任务
    @RequestMapping(value = "/insertDailyTask",method = RequestMethod.GET)
    public Result insertDailyTask(@RequestBody Task task){
        return ResultFactory.buildSuccessResult(taskService.insertTask(task));
    }
    @RequestMapping(value = "/dailyTask",method = RequestMethod.GET)
    public Result dailyTask(@RequestParam String token){
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }
        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
        return ResultFactory.buildSuccessResult(taskService.taskList2UserTrainDto(taskService.getAllTaskList(),userId));
    }

    @RequestMapping(value = "/getSecurityQuestion",method = RequestMethod.POST)
    public Result getSecurityQuestion(@RequestBody User user) {
        User user1=userService.getUserByAccount(user.getAccount());
        List<SecurityQusetion> securityQusetionList=securityQusetionServer.getSecurityQusetion(user1.getUserId());
        List<String> ref=securityQusetionList.stream().map(SecurityQusetion::getQuestion).collect(Collectors.toList());
        return ResultFactory.buildSuccessResult(ref);
    }
    @RequestMapping(value = "/cheakSecurityQuestion",method = RequestMethod.POST)
    public Result cheakSecurityQuestion(@RequestBody AnswerDto answerDto) {
        User user1=userService.getUserByAccount(answerDto.getAccount());
        List<SecurityQusetion> securityQusetionList=securityQusetionServer.getSecurityQusetion(user1.getUserId());
        boolean a=securityQusetionList.get(0).getAnswer().equals(answerDto.getAnswer1());
        boolean b=securityQusetionList.get(1).getAnswer().equals(answerDto.getAnswer2());
        if((securityQusetionList.get(0).getAnswer().equals(answerDto.getAnswer1()) )&&( securityQusetionList.get(1).getAnswer().equals(answerDto.getAnswer2()))){
            StpUtil.setLoginId(user1.getUserId());
            return ResultFactory.buildSuccessResult(StpUtil.getTokenValue());
        }
       return ResultFactory.buildFailResult("问题回答有误");
    }
    //账号注册
    @RequestMapping(value = "/saveSignUpdata", method= RequestMethod.POST)
    public Result   saveSignUpdata(@RequestBody AccountDto accountDto){
        String token=accountDto.getToken();
        if(StpUtil.getLoginIdByToken(token)==null){
            return ResultFactory.buildResultTokenError("token无效");
        }

        Long userId = Long.valueOf(String.valueOf(StpUtil.getLoginIdByToken(token)));
        User user=userService.getUserById(userId);
        user.setPassword(accountDto.getPassword());
        user.setAccount(accountDto.getAccount());
        userService.updateUser(user);
        securityQusetionServer.insert(userId,accountDto.getQuestion1(),accountDto.getAnswer1());
        securityQusetionServer.insert(userId,accountDto.getQuestion2(),accountDto.getAnswer2());
        return ResultFactory.buildSuccessResult(user);
    }
}


